<?php

namespace app\admin\controller;

use app\admin\model\UpmsRole;
use app\admin\model\UpmsUser;
use app\admin\model\UpmsUserPermission;
use app\admin\model\UpmsUserRole;
use app\common\base\BaseController;
use think\Controller;
use think\Db;
use think\exception\DbException;
use think\helper\hash\Md5;
use think\Request;

/**
 * @title 用户中心
 * Class Login
 */
class User extends BaseController
{
    public $table = 'UpmsUser';

    /**
     * 显示资源列表
     *
     * @return array|string
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $this->requestType();
        $type = $this->request->param('type', '');
        $keywords = $this->request->param('keywords', '');
        $locked = $this->request->param('locked', '');

        $where = [];
        if ($locked === '1' || $locked === '0') {
            $where['locked'] = $locked;
        }
        if ($type) {
            switch ($type) {
                case 1:
                    $where['username'] = ['like', "%{$keywords}%"];
                    break;
                case 2:
                    $where['realname'] = ['like', "%{$keywords}%"];
                    break;
                case 3:
                    $where['phone'] = $keywords;
                    break;
            }
        }
        $db = Db::name($this->table)->where($where);
        return $this->_list($db);
    }

    public function _index_data_filter(&$data)
    {
        foreach ($data as &$value) {
            $value['roleId'] = UpmsUserRole::where('user_id', $value['user_id'])->column('role_id');
        }
    }


    /**
     * @title 保存用户
     * @url admin/User/save
     * @method POST
     * @param string username 用户名 空 必须
     * @param string phone 手机号 空 必须
     * @param string password 密码 空 必须
     * @code 1 成功
     * @code 2 失败
     * @return int code 状态码（具体参见状态码说明）
     * @throws \think\exception\DbException
     * @throws \think\Exception
     */
    public function save()
    {
        $this->requestType('POST');
        $user['user_id'] = $this->request->param('id');
        $user['username'] = $this->request->param('username');
        $user['realname'] = $this->request->param('realname');
        $user['password'] = $this->request->param('password');
        $user['phone'] = $this->request->param('phone');
        if (!empty($user['password'])) {
            $md5 = new Md5();
            $user['salt'] = $md5->make(openssl_random_pseudo_bytes(32));
            $md5->setSalt($user['salt']);
            $user['password'] = $md5->make($user['password']);
        } else {
            unset($user['password']);
        }

        if ($user['user_id'] != 0) {
            $user['user_id'] = (UpmsUser::update($user))->user_id;
        } else if (UpmsUser::get(['username' => $user['username']]) || UpmsUser::get(['phone' => $user['phone']])) {
            return $this->buildFailed(0, '用户已经存在');
        } else {
            $user['user_id'] = (UpmsUser::create($user))->user_id;
        }

        if ($user['user_id']) {
            //清除数据
            UpmsUser::get($user['user_id'])->upmsUserRoles()->detach();
            UpmsUser::get($user['user_id'])->upmsUserPermissions()->detach();
            //存角色
            array_key_exists('roleId', $this->request->param()) ? UpmsUser::get($user['user_id'])->upmsUserRoles()->attach($this->request->param()['roleId']) : '';

            if (array_key_exists('permissions', $this->request->param())) {
                //存单独权限
                $havedRoles = UpmsUser::get($user['user_id'])->upmsUserRoles;
                $havedPermissions = [];
                foreach ($havedRoles as $havedRole) {
                    $havedPermissions = array_merge($havedPermissions, UpmsRole::get($havedRole['role_id'])->upmsRolePermissions);
                }
                $permissions = $this->request->param()['permissions'];
                //去重复
                foreach ($havedPermissions as $havedPermission) {
                    foreach ($permissions as $key => $permission) {
                        if ($havedPermission['permission_id'] == $permission) {
                            unset($permissions[$key]);
                        }
                    }
                }
                if (count($permissions) > 0) {
                    UpmsUser::get($user['user_id'])->upmsUserPermissions()->attach($permissions);
                }

            }

            return $this->buildSuccess([]);

        }


        return $this->buildFailed();
    }

    /**
     * 显示指定的资源
     * @return string
     */
    public function read()
    {
        $this->requestType();
        $havedRoles = UpmsUser::get($this->userInfo['user_id'])->upmsUserRoles;
        $havedPermissions = [];
        foreach ($havedRoles as $havedRole) {
            $havedPermissions = array_merge($havedPermissions, UpmsRole::get($havedRole['role_id'])->upmsRolePermissions);
        }
        $havedPermissions = array_merge($havedPermissions, UpmsUser::get($this->userInfo['user_id'])->upmsUserPermissions);
        $access = [];
        foreach ($havedPermissions as $havedPermission) {
            array_push($access, $havedPermission->uri);
        }
        $this->userInfo['access'] = $access;
        return $this->userInfo;
    }


    /**
     * 保存更新的资源
     *
     * @param  \think\Request $request
     * @param  int $id
     * @return \think\Response
     */
    public function change()
    {
        //$this->requestType('POST');
        $user['user_id'] = $this->request->param('id');
        //异或取反
        $user['locked'] = $this->request->param('locked') ^ 1;
        if (UpmsUser::update($user)) {
            return $this->buildSuccess([]);
        }
        return $this->buildFailed();
    }

    /**
     * 删除指定资源
     *
     * @param  int $id
     * @return \think\Response
     */
    public function delete()
    {
        $this->requestType('POST');
        $user_id = $this->request->param('id');
        if (UpmsUser::destroy($user_id)) {
            return $this->buildSuccess([]);
        }
        return $this->buildFailed();
    }
}
